package com.example.demo.game;

import com.example.demo.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

// 匹配器，负责匹配功能

@Component
public class Matcher {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private OnlineUserMapper onlineUserMapper;
    @Resource
    private RoomManager roomManager;

    private Queue<User> normalQueue = new LinkedList<>();
    private Queue<User> highQueue = new LinkedList<>();
    private Queue<User> veryHighQueue = new LinkedList<>();


    // 把玩家放到匹配队列中
    public void add(User user) {
        if(user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.offer(user);
                normalQueue.notify();

            }
            System.out.println("把玩家" + user.getUsername() + " 放到了 normalQueue 中");

        } else if(user.getScore() >= 2000 && user.getScore() < 3000) {
            synchronized (highQueue) {
                highQueue.offer(user);
                highQueue.notify();

            }
            System.out.println("把玩家" + user.getUsername() + " 放到了 highQueue 中");
        }else {
            synchronized (veryHighQueue) {
                veryHighQueue.offer(user);
                veryHighQueue.notify();

            }
            System.out.println("把玩家" + user.getUsername() + " 放到了 veryHighQueue 中");
        }
    }


    // 把玩家从匹配队列中取出来
    public void remove(User user) {
        if(user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.remove(user);

            }
            System.out.println("把玩家" + user.getUsername() + " 移除 normalQueue 中");

        } else if(user.getScore() >= 2000 && user.getScore() < 3000) {

            synchronized (highQueue) {
                highQueue.remove(user);

            }
            System.out.println("把玩家" + user.getUsername() + " 移除 highQueue 中");
        }else {

            synchronized (veryHighQueue) {
                veryHighQueue.remove(user);

            }
            System.out.println("把玩家" + user.getUsername() + " 移除 veryHighQueue 中");
        }

    }
    //创建三个线程 扫描对应的队列

    public Matcher() {

        Thread t1 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(normalQueue);
                }
            }


        };
        t1.start();
        Thread t2 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(highQueue);
                }
            }


        };
        t2.start();
        Thread t3 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(veryHighQueue);
                }
            }


        };
        t3.start();

    }
    private void handlerMatch(Queue<User> matchQueue) {
        synchronized (matchQueue) {


        try {
        //1.检测玩家是否达到 2
            // 达到2 才会被唤醒 while 做循环检测
        while (matchQueue.size() < 2) {

             matchQueue.wait();
        }
        // 2. 取出两个玩家
        User player1 = matchQueue.poll();
        User player2 = matchQueue.poll();
        System.out.println("匹配出2个玩家：" + player1.getUsername()+ "," + player2.getUsername());

        // 3. 获取玩家的 websocket 的会话
        WebSocketSession session1 = onlineUserMapper.getFromGameHall(player1.getUserId());
        WebSocketSession session2 = onlineUserMapper.getFromGameHall(player2.getUserId());
        // 判断
        if(session1 == null) {
            // 如果玩家1 不在线，就把玩家2放回队列中
            matchQueue.offer(player2);
            return;
        }
        if(session2 == null) {
            matchQueue.offer(player1);
            return;
        }
        if (session1 == session2) {
            matchQueue.offer(player1);
            return;
        }
        // 4. 把两个玩家放到游戏房间
        Room room = new Room();
        roomManager.add(room,player1.getUserId(), player2.getUserId());

            // 5. 反馈信息， 匹配到对手了  通过websocket返回一个message matchSuccess
            //玩家1
        MatchResponse response1 = new MatchResponse();
        response1.setOk(true);
        response1.setMessage("matchSuccess");
        session1.sendMessage(new TextMessage(objectMapper.writeValueAsString(response1)));
            //玩家2
        MatchResponse response2 = new MatchResponse();
        response2.setOk(true);
        response2.setMessage("matchSuccess");

        String json2 = objectMapper.writeValueAsString(response2);
        session2.sendMessage(new TextMessage(json2));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        }
    }

}
